package com.lijiajia.cloud.resource.sys.service.numberid;

import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 基于内存实现数字唯一ID生成服务
 *
 * @author lijiajia
 * @since 2019-05-24
 */
@Component
public class MemoryNumberIdService implements NumberIdService {
    private Map<String, AtomicLong> idCaches = new ConcurrentHashMap<>();
    private Map<String, Long> idIncrementCaches = new ConcurrentHashMap<>();

    @Override
    public Number get(String name) {
        assert name != null;
        AtomicLong al = idCaches.get(name);
        if (al == null) {
            al = new AtomicLong();
            idCaches.put(name, al);
        }
        return al.getAndAdd(getIncrement(name));
    }

    @Override
    public String get(String name, String prefix) {
        return get(name, prefix, null);
    }

    @Override
    public String get(String name, String prefix, String suffix) {
        assert name != null;
        prefix = prefix == null ? "" : suffix;
        suffix = suffix == null ? "" : suffix;
        return prefix + get(name) + suffix;
    }

    @Override
    public void setValue(String name, Number value) {
        idCaches.put(name, new AtomicLong(value.longValue()));
    }

    @Override
    public void setIncrement(String name, Number number) {
        idIncrementCaches.put(name, number.longValue());
    }

    private long getIncrement(String name) {
        return idIncrementCaches.computeIfAbsent(name, k -> 1L);
    }
}
